package comc.config;



import comc.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * token验证拦截
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入token拦截器");
        // 取得token
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            throw new Exception("token不存在");
        }
//        if (!tokenHeader.startsWith(JWTUtil.TOKEN_PREFIX)) {
//            throw new Exception("这是你自己造的token吧");
//        }
//        String token = tokenHeader.replace(JWTUtil.TOKEN_PREFIX, "");//真正的token

        String logonName = JWTUtil.getLogonName(token);

        // 验证token是否有效
        if (!JWTUtil.verify(token, logonName, "123456")){
            throw new Exception("token已失效");
        }

        Date tokenTime = JWTUtil.getTokenTime(token);
        System.out.println("token剩余的过期时间时间"+tokenTime);
        long time = tokenTime.getTime();
        if(time>1000){
            String logonName1 = JWTUtil.getLogonName(token);
            String tokenNew = JWTUtil.createToken(logonName1);
            response.setHeader("tokenNew",tokenNew);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

}
